angular.module('masvida.controllers', [])

.controller('TabCtrl', function ($scope, LoginService, $state) {
    $scope.logout = function () {
        $state.go('login');
        LoginService.logout();
    }
})

.controller('AttendanceCtrl', function ($scope, AttendanceService, LoginService, $ionicLoading, $ionicPopup, $state) {

    $scope.doRefresh = function () {
        $scope.data.groups = [];
        $ionicLoading.show({
            template: 'Cargando grupos'
        });
        AttendanceService.getGroups(LoginService.getUserLogged())
        .success(function (data) {
            $ionicLoading.hide();
            $scope.$broadcast('scroll.refreshComplete');
            if (data.Success) {
                $scope.data.groups = data.Groups;
            } else {
                console.log(data.ErrorMessage);
                $ionicPopup.alert({
                    title: 'Error!',
                    template: 'Hubo un error al buscar tus grupos'
                });
            }
        }).error(function (data) {
            console.log(data);
            $ionicLoading.hide();
            $ionicPopup.alert({
                title: 'Error!',
                template: 'Hubo un error al buscar tus grupos'
            });
        });
    };

    $scope.data = {
        groups: {}
    }

    $scope.doRefresh();
})

.controller('AttendanceSummaryCtrl', function ($scope, $stateParams, LoginService, AttendanceService, $ionicLoading, $location, $state) {
    var today = new Date();
    var weekAgo = new Date();
    weekAgo.setDate(today.getDate() - 7);

    $scope.data = {
        groupId: $stateParams.groupId,
        dates: {
            StartDate: weekAgo,
            EndDate: today
        }
    };

    $scope.doRefresh = function () {
        $scope.search($scope.data);
    }

    $scope.attendanceSummaryClass = function (summary) {
        var className = 'item-green';

        if (!summary.Met && summary.Comments == "") {
            className = 'item-red';
        } else if (!summary.Met && summary.Comments != "") {
            className = 'item-yellow';
        }
        return className;
    }

    $scope.search = function (data) {
        $scope.attendanceSummaries = [];
        $ionicLoading.show({
            template: 'Cargando listas'
        });

        var request = LoginService.getUserLogged();
        request.GroupId = $stateParams.groupId;
        request.StartDate = data.dates.StartDate;
        request.EndDate = new Date(data.dates.EndDate.setTime( data.dates.EndDate.getTime() +  86400000 )) ;

        request.StartDate.setHours(0,0,0,0);
        request.EndDate.setHours(0,0,0,0);

        AttendanceService.getAttendances(request)
            .success(function (data) {
                $ionicLoading.hide();
                $scope.$broadcast('scroll.refreshComplete');
                if (data.Success) {
                    $scope.attendanceSummaries = data.AttendanceSummaries;
                } else {
                    console.log(data.ErrorMessage);
                    $ionicPopup.alert({
                        title: 'Error!',
                        template: 'Hubo un error al buscar tus listas de asistencia'
                    });
                }
            }).error(function (data) {
                console.log(data);
                $ionicLoading.hide();
                $ionicPopup.alert({
                    title: 'Error!',
                    template: 'Hubo un error al buscar tus listas de asistencia'
                });
            });
    };

    $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {

        if ($location.path().indexOf("/tab/attendance") > -1) {
            $scope.search($scope.data);
        }

    });
})

.controller('PostAttendanceCtrl', function ($scope, $stateParams, $state, $ionicLoading, $ionicPopup, $ionicHistory, LoginService, AttendanceService) {
    $scope.data = {
        attendanceSummaryId: $stateParams.attendanceSummaryId,
        met: JSON.parse($stateParams.isPosted) ? JSON.parse($stateParams.met) : true,
        comments: $stateParams.comments,
        title: 'Asistencia de ' + $stateParams.date
    };

    var request = LoginService.getUserLogged();
    if(request != undefined && request != null){
      $ionicLoading.show({
          template: 'Cargando miembros'
      });
      request.AttendanceSummaryId = $stateParams.attendanceSummaryId;

      AttendanceService.getAttendanceDetailForAttendanceId(request)
          .success(function (data) {
              $ionicLoading.hide();
              if (data.Success) {
                  $scope.attendances = data.Attendances;
              } else {
                  console.log(data.ErrorMessage);
                  $ionicPopup.alert({
                      title: 'Error!',
                      template: 'Hubo un error al buscar a los miembros'
                  });
              }
          }).error(function (data) {
              console.log(data);
              $ionicLoading.hide();
              $ionicPopup.alert({
                  title: 'Error!',
                  template: 'Hubo un error al buscar a los miembros'
              });
          });
    }else {
      $ionicPopup.alert({
          title: 'Error!',
          template: 'Por favor primero ingresa tus credenciales'
      });
      $state.go('login');
    }
    $scope.cancel = function () {
        $ionicHistory.goBack();
    };

    $scope.save = function () {
        if(!$scope.data.met && $scope.data.comments == ""){
          $ionicPopup.alert({
              title: 'Error!',
              template: 'Por favor agrega un comentario antes de guardar'
          });
          return;
        }

        $ionicLoading.show({
            template: 'Salvando'
        });
        var request = LoginService.getUserLogged();
        var present = 0, total = 0, absent = 0;
        var comments = "";
        if ($scope.data.met) {
            for (var i = 0; i < $scope.attendances.length; i++) {
                if ($scope.attendances[i].IsPresent) {
                    present++;
                }
                total++;
            }
            absent = total - present;
        } else {
            comments = $scope.data.comments;
        }
        request.AttendanceSummary = {
            AttendanceSummaryId: $stateParams.attendanceSummaryId,
            PresentCount: present,
            AbsentCount: absent,
            TotalCount: total,
            Met: $scope.data.met,
            IsScheduled: true,
            IsPosted: true,
            Comments: comments
        };

        AttendanceService.saveAttendance(request)
        .success(function (data) {
            if (data.Success) {

                var attendancesRequest = LoginService.getUserLogged();
                attendancesRequest.AttendanceSummaryId = $stateParams.attendanceSummaryId;
                attendancesRequest.Attendances = [];

                for (var i = 0; i < $scope.attendances.length; i++) {
                    attendancesRequest.Attendances.push({
                        AttendanceId: $scope.attendances[i].AttendanceId,
                        PersonId: $scope.attendances[i].PersonId,
                        IsPresent: $scope.data.met ? $scope.attendances[i].IsPresent : false
                    });
                }

                AttendanceService.saveAttendances(attendancesRequest)
                    .success(function (data) {
                        $ionicLoading.hide();
                        if (data.Success) {
                            $ionicHistory.goBack();
                        } else {
                            console.log(data.ErrorMessage);
                            $ionicPopup.alert({
                                title: 'Error!',
                                template: 'Hubo un error al guardar las asistencias'
                            });
                        }
                    }).error(function (data) {
                        console.log(data);
                        $ionicLoading.hide();
                        $ionicPopup.alert({
                            title: 'Error!',
                            template: 'Hubo un error al guardar las asistencias'
                        });
                    });

            } else {
                console.log(data.ErrorMessage);
                $ionicPopup.alert({
                    title: 'Error!',
                    template: 'Hubo un error al salvar'
                });
            }
        }).error(function (data) {
            console.log(data);
            $ionicLoading.hide();
            $ionicPopup.alert({
                title: 'Error!',
                template: 'Hubo un error al salvar'
            });
        });
    };
})

.controller('LoginCtrl', function ($scope, LoginService, $ionicPopup, $state, $ionicLoading, PushNotificationService) {
    if (LoginService.isUserLogged()) {
        $state.go('tab.attendance');
    }

    $scope.loginTypes = [
        { text: "Portal", value: 1 },
        { text: "Grupo conexion", value: 2 }
    ];
    $scope.user = {};
    $scope.user.loginType = 2;

    $scope.login = function (user) {
        $ionicLoading.show({
            template: 'Cargando...'
        });
        LoginService.loginUser(user.username, user.password, user.loginType)
            .success(function (data) {
                $ionicLoading.hide();
                if (data.Success) {
                    $scope.user.loginType = 2;
                    $scope.user.username = "";
                    $scope.user.password = "";
                    $state.go('tab.attendance');
                    LoginService.saveUser(data);
                    PushNotificationService.register(data);
                } else {
                    $ionicPopup.alert({
                        title: 'Error al ingresar!',
                        template: 'Verifica tus credenciales'
                    });
                }
            }).error(function (data) {
                console.log(data);
                $ionicLoading.hide();
                $ionicPopup.alert({
                    title: 'Error al ingresar!',
                    template: 'Verifica tus credenciales'
                });
            });
    }

});
